package com.adk.backend.service.impl;

import com.adk.backend.entity.*;
import com.adk.backend.mapper.*;
import com.adk.backend.service.SearchService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 搜索服务实现类
 */
@Service
public class SearchServiceImpl implements SearchService {
    
    @Autowired
    private OrderListMapper orderListMapper;
    
    @Autowired
    private ActionLogsMapper actionLogsMapper;
    
    @Autowired
    private OrderTrackingMapper orderTrackingMapper;
    
    @Autowired
    private RecvLogsMapper recvLogsMapper;
    
    @Autowired
    private CtnScanXbLogsMapper ctnScanXbLogsMapper;
    
    @Autowired
    private ShipLogMapper shipLogMapper;
    
    @Autowired
    private BillingListMapper billingListMapper;
    
    @Autowired
    private BillingDetailsMapper billingDetailsMapper;
    
    @Autowired
    private LoadingDetailsMapper loadingDetailsMapper;
    
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    
    @Override
    public Map<String, Object> searchOrder(String orderNo, Long orderId) {
        Map<String, Object> result = new HashMap<>();
        
        Long id = null;
        if (orderNo != null && !orderNo.isEmpty()) {
            LxOrderList order = orderListMapper.selectByOrderNo(orderNo);
            if (order != null) {
                id = order.getId();
            }
        }
        if (id == null && orderId != null && orderId > 0) {
            id = orderId;
        }
        
        if (id == null || id <= 0) {
            result.put("order", null);
            result.put("logList", new ArrayList<>());
            result.put("trackingList", new ArrayList<>());
            result.put("recvLogs", new ArrayList<>());
            result.put("obLogs", new ArrayList<>());
            result.put("shipLogs", new ArrayList<>());
            result.put("opLogs", new ArrayList<>());
            result.put("billing", null);
            result.put("billingDetails", new ArrayList<>());
            return result;
        }
        
        // 查询订单详情
        LxOrderList order = orderListMapper.selectById(id);
        result.put("order", order);
        
        // 查询操作日志（订单表）
        QueryWrapper<LxActionLogs> logWrapper = new QueryWrapper<>();
        logWrapper.eq("tb_name", "order_list")
                  .eq("tb_id", id)
                  .orderByAsc("id");
        List<LxActionLogs> logList = actionLogsMapper.selectList(logWrapper);
        
        // 查询操作日志（发货单表）
        QueryWrapper<LxShipLog> shipLogWrapper = new QueryWrapper<>();
        shipLogWrapper.eq("ol_id", id);
        List<LxShipLog> shipLogs = shipLogMapper.selectList(shipLogWrapper);
        if (!shipLogs.isEmpty()) {
            List<Long> slIds = new ArrayList<>();
            for (LxShipLog sl : shipLogs) {
                slIds.add(sl.getId());
            }
            QueryWrapper<LxActionLogs> slLogWrapper = new QueryWrapper<>();
            slLogWrapper.eq("tb_name", "ship_log")
                       .in("tb_id", slIds)
                       .orderByAsc("id");
            List<LxActionLogs> slLogList = actionLogsMapper.selectList(slLogWrapper);
            logList.addAll(slLogList);
        }
        
        // 按ID排序
        logList.sort(Comparator.comparing(LxActionLogs::getId));
        result.put("logList", logList);
        
        // 查询跟踪记录
        QueryWrapper<LxOrderTracking> trackingWrapper = new QueryWrapper<>();
        trackingWrapper.eq("order_id", id)
                      .orderByAsc("id");
        List<LxOrderTracking> trackingList = orderTrackingMapper.selectList(trackingWrapper);
        result.put("trackingList", trackingList);
        
        // 查询收货记录
        QueryWrapper<LxRecvLogs> recvWrapper = new QueryWrapper<>();
        recvWrapper.eq("tb_ol_id", id)
                  .orderByAsc("id");
        List<LxRecvLogs> recvLogs = recvLogsMapper.selectList(recvWrapper);
        result.put("recvLogs", recvLogs);
        
        // 查询扫描记录
        QueryWrapper<LxCtnScanXbLogs> scanWrapper = new QueryWrapper<>();
        scanWrapper.eq("tb_ol_id", id)
                   .orderByDesc("id");
        List<LxCtnScanXbLogs> obLogs = ctnScanXbLogsMapper.selectList(scanWrapper);
        result.put("obLogs", obLogs);
        
        // 查询发货记录
        result.put("shipLogs", shipLogs);
        
        // 查询费用记录（暂时注释，需要OrderPriceMapper）
        // QueryWrapper<LxOrderPrice> priceWrapper = new QueryWrapper<>();
        // priceWrapper.eq("order_id", id)
        //            .in("fee_type", Arrays.asList(1, 11))
        //            .orderByAsc("id");
        // List<LxOrderPrice> opLogs = orderPriceMapper.selectList(priceWrapper);
        result.put("opLogs", new ArrayList<>());
        
        // 查询账单信息
        if (order != null && order.getIsBill() != null && order.getIsBill() == 1) {
            QueryWrapper<LxBillingList> billingWrapper = new QueryWrapper<>();
            billingWrapper.eq("order_id", id)
                         .orderByDesc("id")
                         .last("LIMIT 1");
            List<LxBillingList> billingList = billingListMapper.selectList(billingWrapper);
            if (!billingList.isEmpty()) {
                LxBillingList billing = billingList.get(0);
                result.put("billing", billing);
                
                // 查询账单明细
                QueryWrapper<LxBillingDetails> detailsWrapper = new QueryWrapper<>();
                detailsWrapper.eq("bill_id", billing.getId())
                             .orderByAsc("id");
                List<LxBillingDetails> billingDetails = billingDetailsMapper.selectList(detailsWrapper);
                result.put("billingDetails", billingDetails);
            } else {
                result.put("billing", null);
                result.put("billingDetails", new ArrayList<>());
            }
        } else {
            result.put("billing", null);
            result.put("billingDetails", new ArrayList<>());
        }
        
        return result;
    }
    
    @Override
    public Map<String, Object> searchLoadingNo(String loadingNo) {
        Map<String, Object> result = new HashMap<>();
        
        QueryWrapper<LxLoadingDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("loading_no", loadingNo)
               .orderByAsc("id");
        List<LxLoadingDetails> list = loadingDetailsMapper.selectList(wrapper);
        
        result.put("list", list);
        return result;
    }
    
    @Override
    public Map<String, Object> searchTradeOrder(String orderNo, Long orderId) {
        Map<String, Object> result = new HashMap<>();
        
        Long id = null;
        if (orderNo != null && !orderNo.isEmpty()) {
            QueryWrapper<LxTradeOrderList> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo)
                   .last("LIMIT 1");
            LxTradeOrderList order = tradeOrderMapper.selectOne(wrapper);
            if (order != null) {
                id = order.getId();
            }
        }
        if (id == null && orderId != null && orderId > 0) {
            id = orderId;
        }
        
        if (id == null || id <= 0) {
            result.put("order", null);
            result.put("logList", new ArrayList<>());
            return result;
        }
        
        // 查询贸易订单详情
        LxTradeOrderList order = tradeOrderMapper.selectById(id);
        result.put("order", order);
        
        // 查询操作日志
        QueryWrapper<LxActionLogs> logWrapper = new QueryWrapper<>();
        logWrapper.eq("tb_name", "trade_order_list")
                  .eq("tb_id", id)
                  .orderByAsc("id");
        List<LxActionLogs> logList = actionLogsMapper.selectList(logWrapper);
        result.put("logList", logList);
        
        return result;
    }
}

